import uuid
import os

import paramiko


# from fabric.api import env, put, get



class cAPI():
    # mHost = cHost('127.0.0.0','root','123')
    def __init__(self):
        pass

    def createGUID(self, name=None):
        guid = uuid.uuid1()
        return guid

    def savefile(self, source, filedir, filename):
        if not os.path.exists(filedir):
            os.makedirs(filedir)
        if filedir[-1] == '/':
            filedir = filedir + '/'
        fullpath = filedir + filename
        with open(fullpath, 'w') as file:
            file.write(source)
            return fullpath
        return None


apiObj = cAPI()


class cHost:
    def __init__(self, ip, user, password):
        self.user = user
        self.ip = ip
        self.password = password

    # 执行远程指令

    def run(self, cmd):
        try:
            ssh = paramiko.SSHClient()

            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh.connect(self.ip, username=self.user, password=self.password)
            for m in cmd:
                stdin, stdout, stderr = ssh.exec_command(m)
                print(stdout.read())
            print("Check Status: %s\tOK\n" % (self.ip))
            ssh.close()
        except:
            print("%s\tError\n" % (self.ip))

    # 创建目录
    def mkdir(self, dirname):
        try:
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh.connect(self.ip, username=self.user, password=self.password)
            # sftp = ssh.open_sftp()
            # sftp.mkdir(dirname)
            tmpdir = str(apiObj.createGUID())
            fullpath = '/home/explorer/test/' + tmpdir + '/' + dirname
            print('fullpath=', fullpath)
            ssh.exec_command('mkdir -p ' + fullpath)
            print("Create folder %s in remote hosts successfully!\n" % fullpath)
            ssh.close()
        except:
            print("Create folder failure!\n")

    # # 上传本地文件
    # def upload(self, uSRC, uDST):
    #     env.user = self.user
    #
    #     env.password = self.password
    #     env.host_string = self.ip
    #     put("%s" % (uSRC), "%s" % (uDST))
    #     print("Upload local file : \"%s\" to Host : %s \"%s\"\n" % (uSRC, self.ip.split(':')[0], uDST))
    #
    # # 从远程主机下载文件到本地主机
    #
    # def download(self, dSRC, dDST):
    #     env.user = self.user
    #
    #     env.password = self.password
    #     env.host_string = self.ip
    #     get("%s" % (dSRC), "%s" % (dDST))
    #     print("Download remote file from : \"%s\" to : %s \"%s\"\n" % (dDST, self.ip.split(':')[0], dSRC))


# hostObj = cHost('10.1.10.95', 'root', '123')
# hostObj = cHost('52.80.161.161','jupyter','yanbo')
hostObj = cHost('192.168.1.250', 'explorer', 'yanbo')
